package com.littlebee.storysuper.tcp;

import android.os.Handler;
import android.os.Message;

import com.littlebee.storysuper.BaseApplication;
import com.littlebee.storysuper.common.sharePrefUtils.SharePrefUtil;
import com.littlebee.storysuper.entry.User;
import com.littlebee.storysuper.utils.GsonUtils;
import com.littlebee.storysuper.utils.LogUtil;
import com.littlebee.storysuper.utils.Utils;
import com.tjstudy.tcplib.RequestCallback;
import com.tjstudy.tcplib.ResponseCallback;
import com.tjstudy.tcplib.TCPClient;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.DataOutputStream;
import java.net.Socket;

/**
 * Created by liaoyong on 26/11/2017.
 */

public class TcpClientUtil {

    private Socket mSocket;
    public static final int mPort = 11000;
    public static final String mIPAddress = "47.92.37.125";
    private TCPClient tcpClient;
    private boolean isTcpConnect;
    private boolean isTcpSync;

    private static TcpClientUtil _instance=null;

    public static TcpClientUtil getInstance(){
        if (_instance == null) {
            _instance = new TcpClientUtil();
        }
        return _instance;
    }

    public void init() {
        JSONObject heartJson = new JSONObject();
        try {
            heartJson.put("msgid", "5");
            heartJson.put("msgdesc", "app keep live");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        tcpClient = TCPClient.build()
                .server(mIPAddress, mPort)
                .breath(heartJson.toString().getBytes(), 30 * 1000)
                .connTimeout(10 * 1000);
    }

    public void sendMessage(String storyId, int pageIndex) {  JSONObject heartJson = new JSONObject();
        try {
            heartJson.put("msgid", 5);
            heartJson.put("msgdesc", "app keep live");
        } catch (JSONException e) {
            e.printStackTrace();
        }

        tcpClient = TCPClient.build()
                .server(mIPAddress, mPort)
                .breath(heartJson.toString().getBytes(), 6 * 1000)
                .connTimeout(10 * 1000);

        String babyid = SharePrefUtil.getInstance(BaseApplication.getInstance()).getStringValue(SharePrefUtil.HASBINDDEVICEID);
        JSONObject sendjson = new JSONObject();
        try {
            sendjson.put("msgid",  SendCmdBean.CMD_SYNC_PAGE_TYPE);
            sendjson.put("msgdesc", "sync story to baby");
            sendjson.put("babyid", babyid);
            sendjson.put("storyid", storyId);
            sendjson.put("pageno", pageIndex + "");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        String sendMess = sendjson.toString();
        LogUtil.d("liaoyong: message"+sendMess);
        tcpClient.request(sendMess.getBytes(), mPort, new RequestCallback() {
            @Override
            public void onTimeout() {
                LogUtil.e("onTimeout:请求超时，稍后重试 ,关闭连接 ");
                TCPClient.closeTcp(mIPAddress, mPort);
            }

            @Override
            public void onFail(Throwable throwable) {
                handlerError(throwable);
            }
        }, responseCallback);
    }

    public void sendMessage(int msgid, ResponseCallback callback) {
        JSONObject heartJson = new JSONObject();
        try {
            heartJson.put("msgid", 5);
            heartJson.put("msgdesc", "app keep live");
        } catch (JSONException e) {
            e.printStackTrace();
        }

        tcpClient = TCPClient.build()
                .server(mIPAddress, mPort)
                .breath(heartJson.toString().getBytes(), 6 * 1000)
                .connTimeout(10 * 1000);

        User user = Utils.getUserEntry();
        String babyid = SharePrefUtil.getInstance(BaseApplication.getInstance()).getStringValue(SharePrefUtil.HASBINDDEVICEID);
        JSONObject sendjson = new JSONObject();
        try {
            if( msgid == 1) {
                sendjson.put("msgid",msgid );
                sendjson.put("msgdesc", "mother connect");
                sendjson.put("myid", user.getMobile());
            } if( msgid == 2) {
                sendjson.put("msgid",msgid );
                sendjson.put("msgdesc", "baby connect");
                sendjson.put("myid", user.getMobile());
            } else if( msgid == 3) {
                sendjson.put("msgid",msgid );
                sendjson.put("msgdesc", "呼叫宝宝");
                sendjson.put("mamaid", user.getMobile());
                sendjson.put("babyid", babyid);
            } else if( msgid == 4) {
                sendjson.put("msgid",msgid );
                sendjson.put("msgdesc", "同步故事给宝宝");
                sendjson.put("babyid", babyid);
                sendjson.put("storyid", "1234");
                sendjson.put("pageno", "1");
            } else if( msgid == 5) {
                sendjson.put("msgid",msgid );
                sendjson.put("msgdesc", "±£ªÓ–≈œ¢");
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        String sendMess = sendjson.toString();
        LogUtil.d("liaoyong: message"+sendMess);
        isTcpConnect = true;
        tcpClient.request(sendMess.getBytes(), mPort, new RequestCallback() {
            @Override
            public void onTimeout() {
                LogUtil.e("onTimeout:请求超时，稍后重试 ,关闭连接 ");
                TCPClient.closeTcp(mIPAddress, mPort);
                isTcpConnect = false;
            }

            @Override
            public void onFail(Throwable throwable) {
                handlerError(throwable);
            }
        }, callback);
    }


    private void handlerError(Throwable throwable) {
        LogUtil.e("handlerError: 网络访问失败:" + throwable.getMessage());
    }

    private ResponseCallback responseCallback = new ResponseCallback() {
        @Override
        public void onRec(Object message) {
            LogUtil.d("liaoyong:onrev socket msg..." + message.toString());
        }

        @Override
        public void onFail(Throwable throwable) {
            handlerError(throwable);
        }
    };

    public boolean isTcpConnect() {
        return isTcpConnect;
    }

    public boolean isTcpSync() {
        return isTcpSync;
    }

    public void setTcpSync(boolean tcpSync) {
        isTcpSync = tcpSync;
    }
}
